const { ipcRenderer } = require('electron')
const { $ } = require('./helper')
const path = require('path')
let musicFilesPath = []

window.addEventListener('DOMContentLoaded', () => {
  //选择文件
  $('select-music-button').addEventListener('click', () => {
    ipcRenderer.send('open-music-file')
  })

  //选择文件后渲染到添加列表
  ipcRenderer.on('selected-file', (event, path) => {
    if (Array.isArray(path)) {
      renderListHtml(path)
      musicFilesPath = path
    }
  })

  //渲染添加文件列表
  const renderListHtml = paths => {
    const musicList = $('musicList')
    const musicItemsHtml = paths.reduce((html, music) => {
      html += `<li class="list-group-item">${path.basename(music)}</li>`
      return html
    }, '')
    musicList.innerHTML = `<ul class="list-group">${musicItemsHtml}</ul>`
  }

  //导入音乐持久化保存
  $('add-music-button').addEventListener('click', () => {
    ipcRenderer.send('add-tracks', musicFilesPath)
  })
})
